<?php
/**
 * The schedule view functions.
 * @author Ian Dunn <scholar42@gmail.com>
 * @version 1.0
 * @since 2013-11-02
 */
require_once 'schedule.php';

class views {

	/***********************/
	/* Month by month View */
	/***********************/

	/**
	 * Exports the data for a month to a file.
	 *
	 * @param year		The year of this entry.
	 * @param month		The month of this entry.
	 * @param m_times	The strings to be exported.
	 * @return			0 on success, -1 on error.
	 */
	static function export_month_data ($year, $month, $m_times) {
		$file_name = sprintf ("%s/%d_%d.php", schedule::sched_dir(), (int)$year, (int)$month);
		$month_file = fopen ($file_name, "w");
		if (!$month_file) {
			return -1;
		}

		$export_string = var_export ($m_times, TRUE);

		fprintf ($month_file, '<?php'. "\n");
		fprintf ($month_file, '$GLOBALS["month_vars"] = ' . "%s;\n", $export_string);
		fprintf ($month_file, '?>' . "\n");

		fclose ($month_file);

		return 0;
	}

	/**
	 * Determine the a string for the month views.
	 *
	 * @param type		The type of this string - either start, stop or due.
	 * @param order		The order object for this string.
	 * @return			The string to be printed in the month view.
	 */
	static function get_string ($type, $order) {
		$ret = sprintf ("<a class='%s' href=\"/view_order.php?order=%d\">Order %d</a>",$type, (int)$order->id(), (int)$order->id());
		return $ret;
	}

	/**
	 * Prints all of the month view data.
	 *
	 * @param orders	The list of order objects to be printed.
	 */
	static function print_month_view ($orders) {
		$fin = array ();
		foreach ($orders as $id => $order) {
			if ($order->maint_order())
				continue;

			$start_str = views::get_string ('start_time', $order);
			$start = getdate($order->start_time * 60);
			$fin[(int)$start['year']][(int)$start['mon']][(int)$start['mday']][] = $start_str;

			$stop_str = views::get_string ('stop_time', $order);
			$stop = getdate($order->stop_time * 60);
			$fin[(int)$stop['year']][(int)$stop['mon']][(int)$stop['mday']][] = $stop_str;

			$due_str = views::get_string ('due_time', $order);
			$dt = new DateTime ($order->deadline);
			$due_time = $dt->getTimeStamp ();
			$due = getdate ($due_time);
			$fin[(int)$due['year']][(int)$due['mon']][(int)$due['mday']][] = $due_str;
		}

		// Print out fin to a file, and use it as a template.

		foreach ($fin as $year => $y_times) {
			foreach ($y_times as $month => $m_times) {
				views::export_month_data ($year, $month, $m_times);
			}
		}
	}

	/*********************/
	/* Week by week view */
	/*********************/

	static function same_week ($time0, $time1) {
		// Determine first day of the week.
		$date0 = getdate ($time0);
		$wd0 = (int)$date0['wday'];
		$first0 = mktime (0, 0, 0, (int)$date0['mon'], (int)($date0['mday'] - $wd0), (int)$date0['year']);

		$date1 = getdate ($time1);
		$wd1 = (int)$date1['wday'];
		$first1 = mktime (0, 0, 0, (int)$date1['mon'], (int)($date1['mday'] - $wd1), (int)$date1['year']);

		return ($first0 == $first1);
	}

	/**
	 * Exports the data for a week view to a file.
	 *
	 * @param year			The year of this week.
	 * @param month			The month of this week.
	 * @param day			The day that corresponds to the saturday of this week.
	 * @param print_array	The array of the strings to be printed.
	 */
	static function export_week_data ($year, $month, $day, $print_array) {
		$file = sprintf ("%s/week_%d_%d_%d.php", schedule::sched_dir(), $year, $month, $day);
		$week_file = fopen ($file, "w");
		if (!$week_file) {
			return -1;
		}
		$export_var = var_export ($print_array, TRUE);
		fprintf ($week_file, '<?php' . "\n");
		fprintf ($week_file, '$GLOBALS["week_vars"] = ' . "%s;\n", $export_var);
		fprintf ($week_file, '?>' . "\n");
		fclose ($week_file);

		return 0;
	}

	/**
	 * Print the weekly views of the schedule.
	 *
	 * @param sched		The schedule to print.
	 */
	static function print_weekly_view ($sched) {
		$times_arr = array ();
		foreach ($sched as $mid => $mach) {
			foreach ($mach as $phase) {
				$pid = $phase->priority;
				$order = new order ($phase->ordId);
				$ret = $order->init ();
				if (!$ret)
					return FALSE;

				if ($order->maint_order()) {
					$str = sprintf ("<a href=\"/view_machine.php?mach=%d\">Maintenance</a>", $mid);
				} else {
					$str = sprintf ("<a href=\"/view_order.php?order=%d\">%d-%d</a>",
						(int)$phase->ordId, (int)$phase->ordId, (int)$pid);
				}

				// Get the start and stop timestamps, and convert to days.
				$start = (60*$phase->est_start_time);
				$stop = (60*$phase->est_stop_time);
				for ($i = $start; $i < $stop; $i += 86400) {
					$time = getdate ($i);
					$times_arr[(int)$time['year']][(int)$time['mon']][(int)$time['mday']][] = $str;
				}
			}
		}

		$last_time = -1;
		$print_array = array ();

		foreach ($times_arr as $year => $y_times) {
			ksort ($y_times);
			foreach ($y_times as $month => $m_times) {
				ksort ($m_times);
				foreach ($m_times as $day => $strings) {
					$proc_time = mktime (0, 0, 0, (int)$month, (int)$day, (int)$year);
					$proc_date = getdate ($proc_time);
					$wday = (int)$proc_date['wday'];

					if (!($last_time == -1 || views::same_week ($proc_time, $last_time))) {
						// The last week was finished, so print it out.
						if (count ($print_array) > 0) {
							$last_date = getdate ($last_time);
							// Move to the end of the week.
							$end_time = mktime (
								0, 0, 0, (int)$last_date['mon'],
								(int)($last_date['mday'] + 6 - $last_date['wday']),
								(int)$last_date['year']
							);
							$end_date = getdate ($end_time);
							views::export_week_data (
								$end_date['year'], $end_date['mon'],
								$end_date['mday'], $print_array
							);
							$print_array = array ();
						}
					}

					foreach ($strings as $string)
						$print_array[$wday][] = $string;

					$last_time = $proc_time;
				}
			}
		}

		if ($last_time != -1) {
			if (count ($print_array) > 0) {
				$last_date = getdate ($last_time);
				// Move to the end of the week.
				$end_time = mktime (
					0, 0, 0, (int)$last_date['mon'],
					(int)($last_date['mday'] + 6 - $last_date['wday']),
					(int)$last_date['year']
				);
				$end_date = getdate ($end_time);
				views::export_week_data (
					$end_date['year'], $end_date['mon'],
					$end_date['mday'], $print_array
				);
				unset ($print_array);
			}			 
		}
	}

	/*******************/
	/* Day by day View */
	/*******************/

	/**
	 * Export the data for a day view.
	 *
	 * @param year		The year of this day.
	 * @param month		The month of this day.
	 * @param day		The day to be exported.
	 * @param d_times	The strings to be printed.
	 */
	static function export_day_data ($year, $month, $day, $d_times) {
		$machs = array();
		$db = new database ();
		$columns = array("id", "name");
		$result = $db->select_entry ("Machines", $columns);
		while ($array = $result->fetch_assoc ()) {
			$machs[$array['id']] = $array['name'];
		}
		$db->close ();

		$filename = sprintf ("%s/%d_%d_%d.php", schedule::sched_dir(), $year, $month, $day);
		$day_file = fopen ($filename, "w");

		$export_array = array();

		foreach (range(0,23) as $hour) {
			$new_ent = array ();

			if (!isset ($d_times[$hour])) {
				$export_array[$hour] = $new_ent;
				continue;
			}

			$machines = $d_times[(int)$hour];
			foreach ($machs as $m => $name) {
				$new_strings = array ();
				foreach ($machines as $mid => $strings) {
					if ($mid == $m) {
						$new_strings = $strings;
						break;
					}
				}
				$new_ent[$m] = $new_strings;
			}
			$export_array[$hour] = $new_ent;
		}

		$export_string = var_export ($export_array, TRUE);
		fprintf ($day_file, '<?php'."\n");
		fprintf ($day_file, '$GLOBALS["day_vars"] = ' . "%s;\n", $export_string);
		fprintf ($day_file, '?>'."\n");
		fclose ($day_file);
	}

	/**
	 * Print the daily views for the schedule.
	 *
	 * @param sched		The schedule to print out.
	 */
	static function print_daily_view ($sched) {
		$times_arr = array ();
		foreach ($sched as $mid => $mach) {
			foreach ($mach as $phase) {
				$pid = (int)$phase->priority;
				// Get the start and stop timestamps, and convert to days.
				$str = sprintf ("<a href=\"/view_order.php?order=%d\">%d-%d</a>",
						(int)$phase->ordId, (int)$phase->ordId, (int)$pid);

				// Get the start and stop timestamps, and convert to days.
				$start = (60*$phase->est_start_time);
				$stop = (60*$phase->est_stop_time);
				for ($i = $start; $i < $stop; $i += 3600) {
					$time = getdate ($i);
					// Will need to make sure that these are in the proper order.
					// Probably means that buffer space will be required.
					$times_arr[(int)$time['year']][(int)$time['mon']][(int)$time['mday']][(int)$time['hours']][$mid][] = $str;
				}
			}
		}

		foreach ($times_arr as $year => $y_times) {
			foreach ($y_times as $month => $m_times) {
				foreach ($m_times as $day => $d_times) {
					views::export_day_data ($year, $month, $day, $d_times);
				}
			}
		}

	}
}
?>